package array;

public class BalancePoint {
  
  //flaw? not work for {1,-1,-1,2}
  public static int bp(int[] arr){
    long sumLeft = arr[0];
    long sumRight = arr[arr.length-1];

    int i=1, j = arr.length-2;

    for (; i<j; ){
      if (sumLeft < sumRight) {
        sumLeft += arr[i++];
      }else if (sumLeft > sumRight) {
        sumRight += arr[j--];
      }else {
        sumLeft += arr[i++];
        sumRight += arr[j--];
      }
    }
    if(sumLeft == sumRight)
      return i;
    else
      return -1;
  }
  
  public static int bp2(int[] a){
    int sum = 0;
    int leftsum =0;
    for (int i = 0; i< a.length; i++)
      sum += a[i];
    
    for(int i = 0; i < a.length; i++){
      sum -= a[i];
      if(leftsum == sum)
        return i;
      leftsum += a[i];
    }
    return -1;
  }

  /**
   * @param args
   */
  public static void main(String[] args) {
    // TODO Auto-generated method stub
    //System.out.println(bp(new int[]{1,2,9,4,-1}));
    System.out.println(bp2(new int[]{1,-1,-1,2}));
  }

}
